
//C++中的String容器，我们在申请空间的时候不需要考虑\0，他会自动帮我们多开辟一个空间去存放\0
#include <iostream>
#include <string>
#include <cstring>

void C_ReplaceBlack(char *str, int length)
{
    // 判断参数是否正确
    if (str == nullptr || length <= 0)
        return;

    // 统计空格的数量，也可以在这里面统计一下实际字符串的长度，防止参数错误
    int count_black = 0;
    for (int i = 0; i < length; i++)
    {
        if (str[i] == ' ')
            count_black++;
    }

    // 确定边界
    int end = length + (count_black * 2);
    int start = length;
    // 移动数据
    while (start >= 0)
    {
        if (str[start] == ' ')
        {
            char buf[4];
            snprintf(buf, 4, "%%%02X", str[start]);
            str[end--] = buf[2];
            str[end--] = buf[1];
            str[end--] = buf[0];
        }
        else
        {
            str[end--] = str[start];
        }
        start--;
    }
}

void Cpp_ReplaceBlack(std::string &str, size_t length)
{
    // 判断参数是否正确
    if (length == 0)
        return;

    // 统计空格的数量
    int count_black = 0;
    for (auto &ch : str)
    {
        if (ch == ' ')
            count_black++;
    }

    // 提前开好空间，确定空间足够
    int start = length;
    int end = length + (2 * count_black);
    str.reserve(end);
    while (start >= 0)
    {
        if (str[start] == ' ')
        {
            str[end--] = '0';
            str[end--] = '2';
            str[end--] = '%';
        }
        else
        {
            str[end--] = str[start];
        }
        start--;
    }
}

int main()
{
    char ch[100] = " ni zui jin zen m   yang a ";
    C_ReplaceBlack(ch, strlen(ch));
    std::cout << ch << std::endl;

    std::string str = " ni zui jin zen m yang a ";
    Cpp_ReplaceBlack(str, str.size());
    std::cout << str.c_str() << std::endl;

    str = "    ";
    Cpp_ReplaceBlack(str, str.size());
    std::cout << str.c_str() << std::endl;
    return 0;
}